package zuel.innovation.disley.user.service;

import cn.fabrice.jfinal.service.BaseService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import zuel.innovation.disley.common.module.Token;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class UserSessionService extends BaseService<Token> {
    public UserSessionService() {
        super("token.", Token.class, "token");
    }

    @Inject
    UserSessionService sessionService;

    public boolean add(int uid, String token) throws ParseException {
        Kv cond = Kv.by("uid", uid);
        List<Token> tokenList = sessionService.list(cond, "addToken");
        for (Token t : tokenList) {
            if (t.getTDeleted() != 1) {
                return false;
            }
        }
        Token userToken = new Token();
        userToken.setUId(uid);
        userToken.setTToken(token);
        userToken.setTDeleted(0);
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date starttime = df.parse(df.format(System.currentTimeMillis()));
        Date endtime = df.parse(df.format(System.currentTimeMillis() + 4 * 60 * 60 * 1000));
        userToken.setTStarttime(starttime);
        userToken.setTEndtime(endtime);
        return userToken.save();
    }

    public Token getByToken(String token) {
        Kv cond = Kv.by("token", token);
        Token token1 = this.get(cond, "getUserByToken");
        return token1;
    }


}
